package com.guguskins.back.common.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * @date 2021/6/9 14:34
 */
@Component
@Slf4j
public class RabbitMQProducers {

    private static RabbitTemplate rabbitTemplate;

    @Autowired
    private void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        RabbitMQProducers.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 设置确认机制
     * 来确保消息投递状态
     */
    private static void setConfirmCallback() {
        // 消息只要被 rabbitmq broker 接收到就会执行 confirmCallback
        // 如果是 cluster 模式，需要所有 broker 接收到才会调用 confirmCallback
        // 被 broker 接收到只能表示 message 已经到达服务器，并不能保证消息一定会被投递到目标 queue 里
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ObjectUtils.isEmpty(correlationData)) {
                String msgId = correlationData.getId();
                if (ack) {
                    log.info(msgId + " : 消息发送成功");
                } else {
                    log.info(msgId + " : 消息发送失败", cause);
                }
            }
            setReturnCallback();
        });
    }

    /**
     * 设置回调机制
     */
    private static void setReturnCallback() {
        rabbitTemplate.setReturnsCallback(returned -> {
            log.info(MessageFormat.format("消息确认失败回调：ReturnCallback：{0},{1},{2},{3},{4}", returned.getMessage(), returned.getReplyCode(), returned.getReplyText(), returned.getExchange(), returned.getRoutingKey()));
            //todo 做消息发送失败时的处理逻辑
        });
    }

    public static void convertAndSend(String exchange, String routingKey, LocalDateTime expTime, Object content) {
        int endTime = (int) (expTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() - System.currentTimeMillis());
        convertAndSend(exchange, routingKey, endTime, content);
    }

    public static void convertAndSend(String exchange, String routingKey, Integer expTime, Object content) {
//        setConfirmCallback();
        //发送延迟消息
        rabbitTemplate.convertAndSend(exchange, routingKey, content, message -> {
//            message.getMessageProperties().setHeader("x-delay",expTime);
            message.getMessageProperties().setDelay(expTime);
            return message;
        }, new CorrelationData(rabbitTemplate.getUUID()));
    }

    public static void convertAndSend(String routingKey, Object content) {
        setConfirmCallback();
        rabbitTemplate.convertAndSend(routingKey, content, new CorrelationData(rabbitTemplate.getUUID()));
    }
}
